package com.grape.juc.safe.communication;

/**
 * 描述:生产消费一个个执行
 * @author: myx
 * @date: 2019-05-08
 * Copyright © 2019-grape. All rights reserved.
 */
public class WaitTest {
    public static void main(String[] args) {
        WaitRes res = new WaitRes();
        WaitIntThradSolve waitIntThradSolve = new WaitIntThradSolve(res);
        WaitOutThradSlove waitOutThradSlove = new WaitOutThradSlove(res);
        waitIntThradSolve.start();
        waitOutThradSlove.start();
    }
}

/**
 * 共享对象
 */
class WaitRes {
    public String userSex;
    public String userName;
    //线程通讯标识
    public boolean flag = false;
}

/**
 * 写线程(解决问题)
 */
class WaitIntThradSolve extends Thread {
    private WaitRes res;

    public WaitIntThradSolve(WaitRes res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (res) {
                if (res.flag) {
                    try {
                        // 当前线程变为等待，但是可以释放锁
                        res.wait();
                    } catch (Exception e) {

                    }
                }
                if (count == 0) {
                    res.userName = "沐宇熙";
                    res.userSex = "男";
                } else {
                    res.userName = "小紅";
                    res.userSex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                // 唤醒当前线程
                res.notify();
            }

        }
    }
}

/**
 * 读线程(解决问题)
 */
class WaitOutThradSlove extends Thread {
    private WaitRes res;

    public WaitOutThradSlove(WaitRes res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            //读线程为什么也要加上synchronized关键字:
            //由于读写同时进行有可能写操作只写出了res.userName，在写res.userSex时写操作吧res.userSex改变了，写出来的值就不正确了
            synchronized (res) {
                if (!res.flag) {
                    try {
                        res.wait();
                    } catch (Exception e) {
                    }
                }
                System.out.println(res.userName + "," + res.userSex);
                res.flag = false;
                res.notify();
            }
        }
    }
}



